package io.github.maojian.bianrysearch;

import org.junit.Test;

/**
 * @Auther: jian.mao
 * @Date: 2022-06-28 10:48
 * @Description: https://leetcode.cn/problems/find-first-and-last-position-of-element-in-sorted-array/
 */
public class Q34 {
    public int[] searchRange(int[] nums, int target) {
        return new int[]{find(nums, target, true), find(nums, target, false)};
    }

    public int find(int[] nums, int target, boolean minType) {
        int left = 0, right = nums.length - 1;
        int ans = -1;
        while (left <= right) {
            int mid = left + (right - left) / 2;
            if (nums[mid] == target) {
                ans = mid;
                if (minType) {
                    right = mid - 1;
                } else {
                    left = mid + 1;
                }
            } else if (target < nums[mid]) {
                right = mid - 1;
            } else {
                left = mid + 1;
            }
        }
        return ans;
    }


    @Test
    public void test() {
        int nums[] = new int[]{5, 7, 7, 8, 8, 10};
        int target = 8;
        int[] rangeArr = searchRange(nums, target);
        System.out.println(rangeArr[0]);
        System.out.println(rangeArr[1]);
    }
}
